package com.kinsin.kinsinutil

import android.view.MotionEvent
import android.view.View
import java.util.WeakHashMap

/**
 * 点击效果工具类
 * @author kinsin
 *
 * 使用示例：<p>
 * // 标准用法（显式访问it）
 * myView.clickEffect1(offset = 8f).also {
 *     it.setOnClickListener { /* 点击逻辑 */ }
 *     it.setOnLongClickListener { /* 长按逻辑 */ }
 * }
 * <p>
 * // 简化写法（使用apply作用域函数）
 * myView.clickEffect1(8f).apply {
 *     setOnClickListener { /* 点击逻辑 */ }
 *     setOnLongClickListener { /* 长按逻辑 */ }
 * }
 */
object ClickEffectUtil {
    private const val LONG_PRESS_TIME = 1000L
    private val pressedViews = WeakHashMap<View, Boolean>()

    fun View.clickEffect1(offset: Float = 4f): View {
        var initialY = 0f
        val longPressRunnable = Runnable {
            pressedViews[this] = true
            performLongClick()
        }

        setOnTouchListener { view, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    initialY = translationY
                    animate().translationY(initialY + offset)
                        .setDuration(100)
                        .start()
                    postDelayed(longPressRunnable, LONG_PRESS_TIME)
                }
                MotionEvent.ACTION_UP -> {
                    removeCallbacks(longPressRunnable)
                    if (!pressedViews.containsKey(view)) {
                        performClick()
                    }
                    pressedViews.remove(view)
                    animate().translationY(initialY)
                        .setDuration(100)
                        .start()
                }
                MotionEvent.ACTION_CANCEL -> {
                    removeCallbacks(longPressRunnable)
                    pressedViews.remove(view)
                    animate().translationY(initialY)
                        .setDuration(100)
                        .start()
                }
            }
            true
        }
        return this
    }
}